package com.good.adminController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.good.entity.Admin;
import com.good.service.AdminService;

@Controller
public class LoginController {
	@Resource(name = "adminServiceImpl")
	private AdminService adminService;

	@RequestMapping(value = "/adLogin", method = RequestMethod.GET)
	public String login() {
		return "/admin/login";
	}

	@RequestMapping(value = "/adLogin", method = RequestMethod.POST)
	public String adLogin(String account, String password, HttpSession session,
			HttpServletRequest request) {
		String code = (String) session.getAttribute("validateCode");
		String submitCode = WebUtils.getCleanParam(request, "validateCode");
		if (submitCode == null || !code.equalsIgnoreCase(submitCode)) {
			return "/admin/login";
		}
		Admin admin = new Admin();
		admin.setAccount(account);
		admin.setPassword(password);
		System.out.println(admin.getAccount() + admin.getPassword());
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(
				admin.getAccount(), admin.getPassword());
		// 记住用户，但还没有认证，例如亚马逊
		token.setRememberMe(true);
		try {
			/**
			 * 如果login方法执行完毕且没有抛出任何异常信息，那么便认为用户认证通过。之后在应用程序任意地方调用SecurityUtils.
			 * getSubject()
			 * 都可以获取到当前认证通过的用户实例，使用subject.isAuthenticated()判断用户是否已验证都将返回true.
			 * 相反 ，如果login方法执行过程中抛出异常，那么将认为认证失败。Shiro有着丰富的层次鲜明的异常类来描述认证失败的原因，
			 * 如代码示例。
			 */
			user.login(token);
			return "/admin/main";
		} catch (UnknownAccountException uae) {
			System.out.println("此用户不存在");
			return "redirect:/adLogin.do";
		} catch (IncorrectCredentialsException ice) {
			System.out.println("密码错误");
			return "redirect:/adLogin.do";
		} catch (LockedAccountException lae) {
			System.out.println("用户被锁定");
			return "redirect:/adLogin.do";
		} catch (AuthenticationException e) {
			token.clear();
			return "redirect:/adLogin.do";
		}
	}

	@RequestMapping(value = "/loginOut")
	public String loginOut() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "index";
	}
}
